#coding:utf-8
'''
create on 2017-04-20

@author:sandy
'''
from twisted.internet import protocol,reactor,task
import logging



class TBaseFactory(protocol.Factory):

    def __init__(self):
        self.__idlist = []#可用id列表
        self.__pmap = {} #所有的protocol

    def checkClients(self, clients):
        pass

    def onTimer(self):
        clients = self.getClients()
        self.checkClients(clients)

    
    def getClients(self):
        return self.__pmap.values()[:]
    
    def createClient(self, pid, addr):
        assert False, u"please override createClient()"
        
    
    def buildProtocol(self, addr):
        if len(self.__idlist)==0:
            logging.warn(u"server full")
            return None
        pid = self.__idlist.pop(0)
        p = self.createClient(pid, addr)
        self.__pmap[pid] = p
        return p
    
    def removeProtocol(self, prot):
        pid = prot.getId()
        p = self.__pmap.get(pid)
        if p!=prot:
            logging.error(u"removeProtocol,  p!=protocol, id=%d", pid)
            return
        else:
            logging.debug(u"removeProtocol sucess ClientIp = %s",p.getIp())
        self.__pmap.pop(pid)
        self.__idlist.append(pid)#回收id


    def getProtocol(self, pid):
        return self.__pmap.get(pid, None)
    
    def checkProtocol(self, proto):
        return self.getProtocol(proto.getId()) == proto 
     

    def broadcast(self, pkt):
        for c in self.__pmap.values():
            c.sendPacket(pkt)

    def start(self, ip, port, maxclientcount, checkinterval=5):
        for i in range(maxclientcount):
            self.__idlist.append(i)
        reactor.listenTCP(port, self, interface=ip)
        #listenTCP() -> (twisted\internet\iocpreactor\reactor.py)startListening() 
        #show "starting on XXX" -> 
        #(twisted\internet\protocol.py)doStart() 
        #show "Starting factory <XXXX instance at 0xXXXXX>"
        l = task.LoopingCall(self.onTimer)
        l.start(checkinterval, False)

    def stop(self):
        pass
